package cn.liao.me;

public class GetMainClass {

    public static void main(String[] args) {

        Class<?> mainClazz = getMainClassFromStackTrace();

        System.out.println(mainClazz.getName());

    }

    private static Class<?> getMainClassFromStackTrace() {
        return deduceMainApplicationClass();
    }

    /**
     * 获得调用栈列表
     * @return
     */
    private static Class<?> deduceMainApplicationClass() {
        try {
            StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace) {
                if ("main".equals(stackTraceElement.getMethodName())) {
                    return Class.forName(stackTraceElement.getClassName());
                }
            }
        }
        catch (ClassNotFoundException ex) {
            // Swallow and continue
        }
        return null;
    }
}
